<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="changeValue" />
        <!-- 树形组件 -->
        <el-tree ref="deptTree" node-key="id" highlight-current default-expand-all :data="depts" :props="defaultProps" :expand-on-click-node="false" @current-change="selectNode" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="space-between">
          <el-button size="mini" @click="sendMuliMessage">群发通知</el-button>
          <el-row>
            <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
            <el-button size="mini" @click="add">excel导入</el-button>
            <el-button size="mini" @click="exportEmployee">excel导出</el-button>
          </el-row>
        </el-row>
        <!-- 表格组件 -->
        <el-table ref="employeeTable" :data="list" row-key="id" @select="selectChange" @select-all="selectChange">
          <el-table-column type="selection" />
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column>
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
      <!-- 上传文件弹层 -->
      <ImportExcel :show-excel-dialog.sync="showExcelDialog" @uploadSucess="getEmployeeList" />
      <!-- 角色弹层 -->
      <el-dialog :visible.sync="showRoleDialog" title="分配角色">
        <!-- 弹层内容 -->
        <!-- checkbox -->
        <el-checkbox-group v-model="roleIds">
          <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
          <el-checkbox
            v-for="item in roleList"
            :key="item.id"
            :label="item.id"
          >{{ item.name }}</el-checkbox>
          <div style="text-align: center;margin-top: 10px;">
            <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
            <el-button size="mini" @click="btnCanc">取消</el-button>
          </div>
        </el-checkbox-group>
      </el-dialog>
      <!-- 群发消息弹层 -->
      <el-dialog title="群发通知" :visible.sync="showMultiMessageDialog">
        <div class="select_users">
          <el-tag
            v-for="item in all_users"
            :key="item.id"
            closable
            @close="delSendUser(item)"
          >@{{ item.username }}</el-tag>
        </div>
        <el-form label-width="80px">
          <el-form-item label="消息等级">
            <el-select v-model="messageForm.type" size="mini">
              <el-option :value="1" label="通知消息" />
              <el-option :value="2" label="提示消息" />
              <el-option :value="3" label="重要消息" />
              <el-option :value="4" label="紧急消息" />

            </el-select>
          </el-form-item>
          <el-form-item label="通知内容">
            <el-input v-model="messageForm.content" type="textarea" :rows="4" place-holder="通知内容的长度在5-100个字符" />
          </el-form-item>
        </el-form>

        <!-- 群发通知 -->
        <template #footer>
          <el-row type="flex" justify="end">
            <el-button size="mini" @click="clearForm">取消</el-button>
            <el-button size="mini" type="primary" @click="btnSendMultiMessage">发送通知</el-button>
          </el-row>
        </template>

      </el-dialog>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { transObjToTree } from '@/utils'
import { getDepartmentApi } from '@/api/department.js'
import { getEmployeeList, exportEmployee, delEmployee, getEmployeeDetail, assignRole } from '@/api/employee.js'
import ImportExcel from './components/import-excel.vue'
import { getEnableRoleList } from '@/api/permission'
import { sendMultiMessageAPI } from '@/api/user'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      list: [],
      depts: [], // 组织数据
      total: 0,
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: '' // 模糊搜索字段
      },
      showExcelDialog: false, // 控制导入弹层的显示和隐藏
      // ---------------员工分配角色-------------
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      currentUserId: null, // 用来记录当前点击的用户id
      selectUser: {}, // key(页码) value 是个数组存储这一页我选择的用户
      showMultiMessageDialog: false,
      messageForm: {
        type: 1, // 1 通知消息 2 提示消息 3  重要消息 4 紧急消息
        content: ''
      }
    }
  },
  computed: {
    all_users() {
      return [...Object.values(this.selectUser).flat()] // 将原来数组进行浅拷贝 摆脱和之前数据关系
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async  getDepartment() {
      this.depts = transObjToTree(await getDepartmentApi(), 0)
      this.queryParams.departmentId = this.depts[0].id
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    selectNode(node) {
      // 点击树时候将当前id的值赋值给key
      console.log(node)
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList()
    },
    async getEmployeeList() {
      // 获取员工列表
      const res = await getEmployeeList(this.queryParams)
      this.list = res.rows
      this.total = res.total
    },
    // handleSizeChange(pageSize) {
    //   // 切换页面条数
    //   // console.log('我是pageSize', pageSize)
    //   this.queryParams.pagesize = pageSize
    //   this.getEmployeeList()
    // }
    async handleCurrentChange(page) {
      // 切换分页
      // console.log('我是current', current)
      this.queryParams.page = page
      await this.getEmployeeList()
      // 切换页码处理选中问题
      this.$refs.employeeTable.store.states.selection = this.selectUser[this.queryParams.page] || []
      this.$refs.employeeTable.store.updateSelectionByRowKey() // 重新计算selection
      this.$refs.employeeTable.store.updateAllSelected() // 计算全选
    },
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    async exportEmployee() {
      const blob = await exportEmployee()
      // FileSaver.saveAs(blob文件，文件名)
      FileSaver.saveAs(blob, '员工信息表.xlsx')
    },
    add() {
      this.showExcelDialog = true
    },
    async confirmDel(id) {
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    // ----------------角色----------
    // 点击角色按钮弹出层
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async btnOk() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    },
    btnCanc() {
      this.roleIds = []
      this.showRoleDialog = false
    },
    // 点击多选框时触发的事件
    selectChange(selectionRows) {
      // console.log(selectionRows)
      this.selectUser = {
        ...this.selectUser,
        [this.queryParams.page]: selectionRows
        // 这么写会先拷贝一份原来的数据
        // 添加到对象里面，如过后面切换了分页，那么会在添加一个新的键值对放在对象里面
        // 如果后面操作的页码前面有了，会覆盖掉前面的键值对，这样就实现了记录不同页码所选中员工
      }
      console.log(this.selectUser)
    },
    // 发送消息
    sendMuliMessage() {
      // 检查是否已经选择了用户
      if (!this.all_users.length) {
        return this.$message.warning('请选择要发送消息的用户')
      }
      // 选中后显示弹层
      this.showMultiMessageDialog = true
    },
    // 删除用户
    delSendUser(item) {
      // 哪一页的item
      // 找到后删除selectUser中的数据
      // 页面上取消勾选
      Object.keys(this.selectUser).forEach(key => {
        const index = this.selectUser[key].findIndex(row => row.id === item.id)
        if (index > -1) {
          this.selectUser[key].splice(index, 1) // 删除存储的数据
          this.$refs.employeeTable.toggleRowSelection(item, false)
        }
      })
      // 使用object.keys方法拿到已经有勾选的页码进行循环遍历
      // this.selectUser[key]存储了每一页所有选中的行，然后查找找到对应的后返回其所在数组的下标
      // 然后接着在第一层循环里面写判断如果下标大于-1说明找到了，直接调用删除数组的方法删除掉
      // 最后调用el组件table事件 第一个值传行对象，第二个值传false（为取消勾选）true（为勾选）
    },
    // 发送消息
    async  btnSendMultiMessage() {
      // 发送之前先检查一下选中的数组长度是否为空，避免删除时全删掉了
      if (!this.all_users.length) {
        return this.$message.warning('发送的用户不能为空')
      }
      // 判断发送的消息不能为空
      if (!this.messageForm.content) {
        return this.$message.warning('消息内容不能为空')
      }
      await sendMultiMessageAPI({
        userIds: this.all_users.map(item => item.id),
        ...this.messageForm
      })
      this.$message.success('群发消息成功')
      this.clearForm()
    },
    // 取消
    clearForm() {
      // 重置
      this.messageForm = {
        tupe: 1,
        context: ''
      }
      // 关闭弹层
      this.showMultiMessageDialog = false
    }
  }
}
</script>

    <style lang="scss" scoped>
    .app-container {
    background: #fff;
    display: flex;
    .left {
      width: 280px;
      padding: 20px;
      border-right: 1px solid #eaeef4;
    }
    .right {
      flex: 1;
      padding: 20px;
      .opeate-tools {
        margin:10px ;
      }
      .username {
        height: 30px;
        width: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #04C9BE;
        font-size: 12px;
        display:inline-block;
      }
    }
    .select_users {
  display: flex;
  flex-wrap: wrap;
  padding: 10px 10px;
  border: 1px solid #ccc;
  border-radius: 10px;
  span {
    margin: 6px 5px;
  }
}
  }

</style>
